import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { Card, message, Pagination, Table, Button, Upload } from 'antd';
import PropTypes from 'prop-types';
import { filterAuth } from '@/support/common';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import styles from '@/components/common/PateoTable/TableList.less';
import { PlusOutlined } from '@ant-design/icons';
import moment from 'moment'
import DetailModal from './detailModal';
import { windowUrl } from '@/../public/global';
import { getToken, getMd5 } from '@/utils/utils';
import * as G from '@/utils/common';
import BurgingModal from './burningModal';
import { getDicByKey, getDictOptionsByCode } from '@/support/common';

const mapStateToProps = (state: any) => ({
  burningVehicle: state.burningVehicle,
  loading: state.loading.models["burningVehicle"],
})
class BurningVehicle extends PureComponent<any, any> {
  uploadRef = React.createRef() 
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.array
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      brandList: [], // 品牌
      seriesList: [], //  车系
      vehicleTypeList: [],  //  车型
      modalVisible: false,
      formData: {},
      detailVisible: false, //  详情
      currentSid: '', //  当前详情车辆sid
      uploadSid: '',  //  上传报告（sid）
    }
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'burningVehicle/getFetchPage',
      payload: { 
        url: '/battery/monitor/selfIgnition/page',
        ...formValues,
      },
    });
    this.getBrandData()
  }

  //  获取品牌数据列表
  getBrandData = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'burningVehicle/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.setState({
            brandList: res.data.map((item: any) => ({
              label: item.brandName,
              value: item.brandCode
            })),
            seriesList: [],
            vehicleTypeList: [],
          })
        }
      }
    })
  }

  //  获取车系数据列表
  getSeriesData = (t: any) => {
    const { dispatch } = this.props;
    const brandId = this.searchForm.current.getFieldValue('brandCode')
    //  重置车系、车型
    this.searchForm.current.resetFields(['seriesCode', 'typeCode']);
    this.setState({
      seriesList: [],
      vehicleTypeList: [],
    })
    brandId && dispatch({
      type: 'burningVehicle/getDataWithRes',
      payload: {
        url: '/common/vehicle/getserieslist',
        brandId,
      },
      callback: (res: any) => {
        this.setState({
          seriesList: res.data.map((item: any) => ({
            label: item.name,
            value: item.code,
          })),
        });
      },
    })
  }

  //  获取车型数据列表
  getVehicleTypeData = (t: any) => {
    const { dispatch } = this.props;
    this.setState({ vehicleTypeList: [] });
    this.searchForm.current.resetFields(['typeCode']);
    const brandId = this.searchForm.current.getFieldValue('brandCode');
    const seriesId = this.searchForm.current.getFieldValue('seriesCode');
    brandId && seriesId && 
      dispatch({
        type: 'burningVehicle/getDataWithRes',
        payload: {
          url: '/common/vehicle/gettypelist',
          brandId,
          seriesId,
        },
        callback: (res: any) => {
          this.setState({
            vehicleTypeList: res.data.map((item: any) => ({
              label: item.name,
              value: item.code,
            })),
          });
        }
      })
  }

  handleFormReset = (fields: any) => {
    this.setState({
      formValues: {},
      seriesList: [],
      vehicleTypeList: [],
    })
  }

  dataFormat = (fields: any) => {
    if (G.isNotEmptyAndNil(fields['beginDate'])) {
      fields['beginDate'] = moment(fields.beginDate).format('YYYY-MM-DD HH:mm:ss');
    }
    if (G.isNotEmptyAndNil(fields['endDate'])) {
      fields['endDate'] = moment(fields.endDate).format('YYYY-MM-DD HH:mm:ss');
    }
    return {...fields};
  };

  //  新增
  handleAdd = () => {
    this.setState({
      modalVisible: true, 
      formData: {},
    });
  };

  //  编辑
  handleEdit = (data: any) => {
    const { sid, vin, happenDate, address, status, remark, } = data
    this.setState({
      modalVisible: true,
      formData: {
        sid,
        vin,
        happenDate: moment(happenDate),
        address,
        status: status + '',
        remark
      },
    });
  }

  closeBurningModal = () => {
    this.setState({
      modalVisible: false,
      currentActionType: 'add',
      formData: {}
    });
  };

  handleFreshPage = () => {
    const { dispatch } = this.props
    const { formValues } = this.state;
    dispatch({
      type: 'burningVehicle/getFetchPage',
      payload: { 
        url: '/battery/monitor/selfIgnition/page',
        ...formValues,
      },
    });
  }

  //  删除
  handleDelete = (sid: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'burningVehicle/delData',
      payload: { url: `/battery/monitor/selfIgnition?sid=${sid}` },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('删除成功')
          this.handleFreshPage()
        }
      },
    });
  };

  //  详情打开
  openDetailModal = (record: any) => {
    this.setState({
      detailVisible: true,
      currentSid: record.sid,
    });
  }

  //  详情关闭
  closeDetailModal = () => {
    this.setState({
      detailVisible: false,
      currentSid: '',
    });
  }

  //  上传报告
  handleUpload = (config: any) => {
    const { uploadSid } = this.state
    const { dispatch } = this.props
    const formData = new FormData();
    formData.append('file', config.file);
    const uploadUrl = `/battery/monitor/selfIgnition/record/upload?sid=${uploadSid}`
    // const url = `${windowUrl}${uploadUrl}`;
    // const md5 = getMd5(`sid=${uploadSid}`)
    dispatch({
      type: 'http/postFormData',
      payload: {
        url: uploadUrl,
        formData: formData,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('上传报告成功')
          this.handleFreshPage()
        }
      }
    })
  }

  render() {
    const { burningVehicle: {
      pageData: { list, pagination },
    }, loading, location: { pathname = '/' } } = this.props
    const { formValues, brandList, seriesList, vehicleTypeList, modalVisible, formData, currentSid, detailVisible, uploadSid } = this.state;
    const burningStatus = getDictOptionsByCode(this.context.dicData, 'burningStatus')

    const page = {
      current: pagination.pageNo || 1,
      pageSize: pagination.pageSize,
      total: pagination.totalSize,
    }

    const searchItems = [
      {
        title: '品牌',
        type: 'select',
        selectOptions: brandList,
        onChange: (e: any) => {
          this.getSeriesData(e)
        },
        keyValue: ['value', 'label'],
        key: 'brandCode'
      },
      {
        title: '车系',
        type: 'select',
        selectOptions: seriesList,
        onChange: (e: any) => {
          this.getVehicleTypeData(e)
        },
        keyValue: ['value', 'label'],
        key: 'seriesCode'
      },
      {
        title: '车型',
        type: 'select',
        selectOptions: vehicleTypeList,
        key: 'typeCode'
      },
      {
        title: 'VIN',
        type: 'input',
        key: 'vin',
        maxLength: 18,
      },
      {
        title: '自燃日期起',
        type: 'datePicker',
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
        key: 'beginDate',
      },
      {
        title: '自燃日期止',
        type: 'datePicker',
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
        key: 'endDate',
      },
      {
        title: '自燃时车辆状态',
        type: 'select',
        selectOptions: burningStatus || [],
        key: 'status',
      },
    ]

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...page,
      showTotal: () => (
        <span>共&nbsp;{page?.total}&nbsp;条</span>
      ),
    }

    const columns = [
      {
        title: '品牌',
        dataIndex: 'brandName',
      },
      {
        title: '车系',
        dataIndex: 'seriesName',
      },
      {
        title: '车型',
        dataIndex: 'typeName',
      },
      {
        title: 'VIN码',
        dataIndex: 'vin',
      },
      {
        title: '自燃日期',
        dataIndex: 'happenDate',
      },
      {
        title: '自燃地点',
        dataIndex: 'address',
      },
      {
        title: '自燃时车辆状态',
        dataIndex: 'status',
        render: (text: any, record: any) => {
          return getDicByKey(this.context.dicData, 'burningStatus', text + '');
        }
      },
      {
        title: '累计里程',
        dataIndex: 'accruedMiles',
      },
      {
        title: '车龄',
        dataIndex: 'vehicleAge',
      },
      {
        title: '自燃报告',
        dataIndex: 'report',
        render: (text: any, record: any) => {
          return text && text.length > 0 ? <a href={text} target="_blank" >查看</a> : '';
        }
      },
      {
        title: '备注记录',
        dataIndex: 'remark',
      },
      {
        title: '操作',
        dataIndex: 'opt',
        width: 240,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '详情',
              key: 'detail',
              auth: 'burningVehicle_doDetail',
              onConfirm: () => {
                this.openDetailModal(record)
              },
            },
            {
              title: '编辑',
              key: 'edit',
              auth: 'burningVehicle_doEdit',
              onConfirm: () => {
                this.handleEdit(record)
              },
            },
            {
              title: '删除',
              key: 'del',
              auth: 'burningVehicle_doDel',
              message: '是否确认删除？',
              Popconfirm: true,
              onConfirm: () => {
                this.handleDelete(record.sid)
              },
            },
            {
              title: '上传报告',
              key: 'reported',
              auth: 'burningVehicle_doReported',
              onConfirm: () => {
                this.setState({
                  uploadSid: record.sid
                }, () => {
                  const btn = document.getElementById('btn');
                  btn && btn.click()
                })
                
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={4} pathname={pathname} />;
        }
      },
    ]

    const tableProps = {
      columns,
      dataSource: list,
      loading,
      pagination: paginationProps,
      scroll: { x: 'max-content' }
    }

    const formItems = [
      {
        type: 'input',
        title: 'VIN码',
        key: 'vin',
        rules: [{ required: true, message: '请输入VIN码', whitespace: true }],
        maxLength: 200,
      },
      {
        type: 'datePicker',
        title: '自燃日期',
        key: 'happenDate',
        format: 'YYYY-MM-DD HH:mm:ss',
        showTime: true,
        rules: [{ required: true, message: '请输入自燃日期' }],
        maxLength: 200,
      },
      {
        type: 'input',
        title: '自燃地址',
        key: 'address',
        maxLength: 200,
      },
      {
        type: 'select',
        title: '自燃时车辆状态',
        key: 'status',
        selectOptions: [
          {label: '充电', value: 0},
          {label: '行驶', value: 1},
          {label: '停放', value: 2},  //  配置数据字典
        ],
        rules: [{ required: true, message: '请选择自燃时车辆状态' }],
        keyValue: ['value', 'label'],
        maxLength: 200,
      },
      {
        type: 'textArea',
        title: '备注记录',
        key: 'remark',
        maxLength: 2000,
      },
    ];

    const uploadUrl = `/battery/monitor/selfIgnition/record/upload?sid=${uploadSid}`
    const url = `${windowUrl}${uploadUrl}`;
    const md5 = getMd5(`sid=${uploadSid}`)


    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'burningVehicle/getFetchPage',
              url: '/battery/monitor/selfIgnition/page',
              extraArgs: {},
            }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
            handleFieldsValue={this.dataFormat}
          />
        </Card>
        <Card className={styles.standardTable}>
          <div className="my_newItem">
            <Button size="small" icon={<PlusOutlined />} type="primary" onClick={this.handleAdd}>
              新增
            </Button>
          </div>
          <div style={{
            display: 'none'
          }}>
            {/* <input type="file" name="" id="inp1" /> */}
            <Upload 
              ref={this.uploadRef}
              multiple={false}
              showUploadList={false}
              onChange={this.handleFileChange}
              customRequest={this.handleUpload}
            ><a id="btn" href="javascript:void(0)"></a></Upload>
            
          </div>
          <PateoTable
            extraHandle={true}
            currentName={"page"}
            pageSizeName={"size"}
            tableProps={tableProps}
            fetchParams={{ type: 'burningVehicle/getFetchPage', url: '/battery/monitor/selfIgnition/page' }}
            formValues={formValues}
          />
        </Card>

        <BurgingModal
          modalVisible={modalVisible}
          formData={formData}
          closeModal={this.closeBurningModal}
          freshPage={this.handleFreshPage}
        ></BurgingModal>

        <DetailModal 
          onRef={(val: any) => (this.detailModal = val)}
          sid={currentSid}
          modalVisible={detailVisible}
          closeModal={this.closeDetailModal}
        />
      </div>
    )
  }

}
export default connect(mapStateToProps)(BurningVehicle);
